<template>
  <div class="content_table_List" id="content_table_List">
    <baseTable v-show="!tableShow" :columns="columns.contentManageColumn" :dataSource="resData" :isSelect="true"
      :scroll="scroll" ref="tagBaseTables" :isShowPagination="isShowPagination" :showCheckDelete="showCheckDelete"
      :simple="true" :pageSize="pageSize" :pageCurrent="pageCurrent" :total="props.configData.total"
      @changePage="changePage">

      <template #bodyCell="{ column, text, record, index }">
        <template v-if="column.ellipsis && column.dataIndex !== 'title'">
          <table-tool-tip :text="text" :column="column"></table-tool-tip>
        </template>
        <template v-if="column.dataIndex === 'title'">
          <div class="left-title">
            <div class="title-box">
              <a @click.stop="selectColumn(record)">
                <p class="channelName-content" :style="{ 'min-width': ((record.channelName.length + 1) * 14) + 'px' }">{{
                  '[' +
                  record.channelName + ']' }}</p>
              </a>
              <p class="title-text" @click.stop="eidtRecord(record)">
                {{ record.title }}
              </p>
              <a-tooltip v-if="record.isTop">
                <template #title>已置顶</template>
                <i class="iconfont icon-a-Pinnedtotop1" style="margin-right: 4px; color: #1f6ded;"></i>
              </a-tooltip>
              <a-tooltip v-for="(type, index) in record.types">
                <template #title>{{ type?.typeName }}</template>
                <img :src="type?.logoUrl" alt="" class="tabletypeImg" />
              </a-tooltip>
              <!-- <i v-show="record.isTop" class="iconfont icon-a-Pinnedtotop1" style="margin-left: 8px;color: #1f6ded;"></i>
              <i v-show="record.isTop" class="iconfont icon-a-Firstpush" style="margin-left: 4px;"></i>
              <i v-show="record.isTop" class="iconfont icon-hot" style="margin-left: 4px;"></i> -->
            </div>
            <!-- <span v-else>{{ record.xwly }}</span> -->
          </div>
        </template>
        <template v-if="column.dataIndex === 'status'">
          <span class="xwtype shtype" :class="'type' + text">{{
            getRecordValue(text)
          }}</span>
        </template>
        <template v-if="column.dataIndex === 'oparation'">
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('publishAble') }"
            v-if="record.status != 3 && record.status != 5 && record.status != 6" @click="releaseRecord(record)">发布</a>
          <a class="eidtRecords" @click="eidtRecord(record)" v-if="record.status != 3">详情</a>
          <a class="eidtRecords"
            :class="{ disable: record.isTop ? !btnPerm.includes('cancelTopAble') : !btnPerm.includes('topAble') }"
            @click.stop="singleHandleTop(record)">{{ record.isTop ? '取消置顶' :
              '置顶'
            }}</a>
          <a class="eidtRecords" :class="{ disable: !btnPerm.includes('offlineAble') }" @click="offlineRecord(record)"
            v-if="record.status == 5">下线</a>
          <a-popover placement="bottomRight" v-if="record.status != 3">
            <template #content>
              <a-checkbox-group :value="record.types && record.types.map((obj: any) => obj.id)"
                :disabled="!btnPerm.includes('editContentTypeAble')" class="contentTypeImg">
                <a-checkbox v-for="checkItem in props.contentData" :value="checkItem.id" class="checkboxs"
                  @change="checkboxs($event, checkItem, index)">
                  <div class="typeImgBox">
                    <img :src="checkItem.logoUrl" alt="" class="typeImg" />
                    <span>{{ checkItem.typeName }}</span>
                  </div>
                </a-checkbox>
              </a-checkbox-group>
            </template>
            <a class="eidtRecords more" :class="{ disable: !btnPerm.includes('editContentTypeAble') }">内容类型</a>
          </a-popover>
          <a class="eidtRecords" v-if="record.status == 3" @click.stop="auditProgress(record)">审核进度</a>
          <a class="eidtRecords" @click="urgeRecords(record)" v-if="record.status == 3">审核催办</a>
          <a class="eidtRecords" @click="revocationRecords" v-if="record.status == 3">撤回审核</a>
          <a-popconfirm placement="topRight" :disabled="!btnPerm.includes('deleteAble')"
            @confirm="fetchContentRecycle([record.id])" class="eidtRecords" v-if="record.status != 3">
            <template #title>
              <p style="width: 197px">是否将此内容移入回收站？</p>
            </template>
            <a :class="{ disable: !btnPerm.includes('deleteAble') }">删除</a>
          </a-popconfirm>
          <a-popover placement="bottomRight" overlayClassName="a-content-btns-popover">
            <template #content>
              <a-popconfirm placement="topRight" :disabled="!btnPerm.includes('deleteAble')"
                @confirm="fetchContentRecycle([record.id])" style="margin-left:16px" class="eidtRecords">
                <template #title>
                  <p style="width: 197px">是否将此内容移入回收站？</p>
                </template>
                <a :class="{ disable: !btnPerm.includes('deleteAble') }">删除</a>
              </a-popconfirm>
              <a class="eidtRecords" @click="viewPage(record.previewUrl, 1)"
                :class="{ 'disable': !record.previewUrl || !btnPerm.includes('previewAble') }"
                v-if="record.status != 3">预览</a>
              <a class="eidtRecords" v-if="record.scanUrl"
                :class="{ 'disable': !record.scanUrl || record.status != 5 || !btnPerm.includes('scanAble') }"
                @click="viewPage(record.scanUrl, 2)">浏览</a>
              <a class="eidtRecords" :class="{ disable: !btnPerm.includes('pushAble') }" @click="pushRecord(record)"
                v-if="record.status == 5">推送</a>
              <a class="eidtRecords" :class="{ disable: !btnPerm.includes('moveAble') }" @click="moveRecords(record)"
                v-if="record.status != 3">移动</a>
              <a class="eidtRecords" :class="{ disable: !btnPerm.includes('archiveAble') }"
                @click.stop="singleMergeDom(record)" v-if="record.status != 3">归档</a>
              <a class="eidtRecords" :class="{ disable: !btnPerm.includes('scanHistoryAble') }"
                @click="historyRecord(record)" v-if="record.status == 5 || record.status == 7">浏览记录</a>
              <a v-if="record.status != 3" class="eidtRecords"
                :class="{ disable: !btnPerm.includes('relatedContentAble') }"
                @click.stop="correlationRecord(record)">相关内容</a>
              <a v-if="record.status != 3" class="eidtRecords"
                :class="{ disable: !btnPerm.includes('operationHistoryAble') }"
                @click.stop="operatingRecord(record)">操作记录</a>
            </template>
            <a class="more">...</a>
          </a-popover>
        </template>
      </template>
      <template #otherOpration>
        <a-dropdown :disabled="!rowSelection.length" :placement="scroll.isFixed ? 'top' : 'bottom'">
          <template #overlay>
            <a-menu @click="handleMenuClick">
              <a-menu-item key="3" :disabled="!btnPerm.includes('moveAble')"> 移动 </a-menu-item>
              <a-menu-item key="5" :disabled="!btnPerm.includes('pushAble')"> 推送 </a-menu-item>
              <a-menu-item key="6" :disabled="!btnPerm.includes('archiveAble')"> 归档 </a-menu-item>
            </a-menu>
          </template>
          <a-button :style="{ 'margin-left': '16px' }">
            内容操作
            <DownOutlined />
          </a-button>
        </a-dropdown>
        <a-popover placement="bottomRight" v-if="rowSelection.length">
          <template #content>
            <a-checkbox-group v-model:value="contType" :disabled="!btnPerm.includes('editContentTypeAble')"
              class="contentTypeImg">
              <a-checkbox v-for="checkItem in props.contentData" :value="checkItem.id" class="checkboxs"
                @change="contTypeChek">
                <div class="typeImgBox">
                  <img :src="checkItem.logoUrl" alt="" class="typeImg" />
                  <span>{{ checkItem.typeName }}</span>
                </div>
              </a-checkbox>
            </a-checkbox-group>
          </template>
          <a-button :disabled="!btnPerm.includes('editContentTypeAble')" :style="{ margin: '0 8px' }">内容类型</a-button>
        </a-popover>
        <a-dropdown v-else>
          <template #overlay>
            <a-menu>
            </a-menu>
          </template>
          <a-button :disabled="!rowSelection.length" :style="{ 'margin': '0 8px' }">
            内容类型
            <DownOutlined />
          </a-button>
        </a-dropdown>
        <a-button :style="{ 'margin-left': '8px' }" @click="deleteSelectedAll"
          :disabled="!rowSelection.length || !btnPerm.includes('deleteAble')">删除</a-button>
        <a-button v-show="scroll.isFixed" :style="{ 'margin-left': '8px' }" @click="publishAll()"
          :disabled="!rowSelection.length || !btnPerm.includes('publishAble')">发布</a-button>
        <a-button v-show="scroll.isFixed" :style="{ 'margin-left': '8px' }" @click="offlineRecordAll()"
          :disabled="!rowSelection.length || !btnPerm.includes('offlineAble')">下线</a-button>
        <a-button v-show="scroll.isFixed" :style="{ 'margin-left': '8px' }" @click="handleMenuClick({ key: 1 })"
          :disabled="!rowSelection.length || !btnPerm.includes('topAble')">置顶</a-button>
        <a-button v-show="scroll.isFixed" :style="{ 'margin-left': '8px' }" @click="handleMenuClick({ key: 2 })"
          :disabled="!rowSelection.length || !btnPerm.includes('cancelTopAble')">取消置顶</a-button>
      </template>
    </baseTable>
    <contentMove v-if="isMoveVisible" :isVisible="isMoveVisible" :contentIds="contentId" @handleOk="handleOk"
      @handleCancle="isMoveVisible = false"></contentMove>
    <contentPush v-if="isPushVisible" :isVisible="isPushVisible" :contentIds="contentId" @handleOk="handleOk"
      @handleCancle="isPushVisible = false" :disableCheckbox="disableCheckboxId"></contentPush>
    <browsingHistory v-if="isHistoryVisible" :isVisible="isHistoryVisible" :contentIds="contentId" @handleOk="handleOk"
      @handleCancle="isHistoryVisible = false"></browsingHistory>
    <sortModel v-if="isSortVisible" :isVisible="isSortVisible" :contentIds="contentId" @handleOk="handleOk"
      @handleCancle="isSortVisible = false"></sortModel>
    <correlationModel v-if="isCorrelationVisible" :isVisible="isCorrelationVisible" :contentId="contentIdDetail"
      @handleOk="handleOk" @handleCancle="isCorrelationVisible = false"></correlationModel>
    <operatingRecordmodel v-if="isoperatingVisible" :isVisible="isoperatingVisible"
      @handleCancle="isoperatingVisible = false" :contentId="contentIdDetail"></operatingRecordmodel>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick, createVNode, computed, watch } from "vue";
import { UserOutlined, DownOutlined } from "@ant-design/icons-vue";
import tableToolTip from "@/components/table/tableToolTip.vue";
import contentMove from "./contentMove.vue";
import contentPush from "./contentPush.vue";
import browsingHistory from "./browsingHistory.vue";
import sortModel from "./sortModel.vue";
import { scrollType } from "@/type.d";
import { useRouter } from "vue-router";
import operatingRecordmodel from "./newContent/operatingRecord.vue";
import correlationModel from "./newContent/correlationModel.vue";
import columns from "@/components/table/tableConfig/tableColumn/contentManageColumn";
import Sortable from "sortablejs";
import { getTableScroll } from "@/components/table/tableConfig/table";
import { Modal, message } from "ant-design-vue";
import baseTable from "@/components/table/baseTable.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import request from "@/api/index";
import { routerPerm } from '@/utils/common';
const btnPerm = ref<any[]>([]);
const props = defineProps({
  configData: {
    type: Object,
    default: {},
  },
  isOpen: {
    type: Boolean,
    default: true,
  },
  channelId: {
    type: [Number, String],
    default: null,
  },
  contentData: {
    default: [] as any[],
  },
  pageSize: {
    type: Number,
    default: 20,
  },
  pageCurrent: {
    type: Number,
    default: 1,
  },
});
let dataList = ref<dataSourceType[]>([]); //表格数据源
const isShowPagination = ref<boolean>(true); // 是否需要配分页器
const showCheckDelete = true; // 是否需要分页器中的自定义
const isMoveVisible = ref(false); //控制是否展示移动对话框
const isPushVisible = ref(false); //控制是否展示推送对话框
const isHistoryVisible = ref(false); //控制是否展示浏览记录对话框
const isSortVisible = ref(false); //控制是否展示排序对话框
const isCorrelationVisible = ref(false); //控制是否展示相关内容对话框
let isoperatingVisible = ref(false); //控制是否展示操作记录对话框
const contentIdDetail = ref<number>(0);
const router = useRouter();
let tableShow = ref<Boolean>(false); // 表格显示隐藏，用于refresh数据用的
const contentId = ref<any[]>([]);
const disableCheckboxId = ref<any>(null)
const tagBaseTables = ref<any>({
  selectedRowKeys: [],
}); //
let rowSelection = ref<(string | number)[]>([]);
const contType = ref<any[]>([]);
// 当前页和数量
const pageCurrent = ref<number>(props.configData.current || 1);
const pageSize = ref<number>(props.configData.size || 20);
const resData = ref(props.configData.records);
let scroll: scrollType = reactive({ y: "", isFixed: false, x: '100%' });
nextTick(() => {
  let obj = getTableScroll(20, "content_table_List", -42);
  scroll.y = obj.y;
  scroll.isFixed = obj.isFixed;
});
//watch
// watch(() => [props.configData.size, props.configData.current], ([size, current]) => {
//   console.log(size, current, 'size, current')
//   pageSize.value = size;
//   pageCurrent.value = current;
// }, { deep: true })
//computed
dataList = computed(() => {
  return JSON.parse(JSON.stringify(resData.value));
});

// computed
rowSelection = computed(() => {
  return tagBaseTables?.value?.selectedRowKeys || [];
});


// 多选修改内容类型
const contTypeChek = () => {
  contentId.value = tagBaseTables.value.selectedRowKeys;
  nextTick(() => {
    // resData.value.map=((item:any)=>{
    //   item.tyeps=contType.value
    // })
    fetchContentChangeTypes(contType.value, contentId.value);
    emit("changePage", {
      pageCurrent: pageCurrent.value,
      pageSize: pageSize.value
    });
  });
};
// 修改内容类型
const checkboxs = (item: any, checkItem: any, index: any) => {
  resData.value[index].types
    ? resData.value[index].types
    : (resData.value[index].types = []);
  if (item.target.checked) {
    resData.value[index].types.push(checkItem);
  } else {
    let lsit = resData.value[index].types;
    lsit.forEach((data: any, indexs: any) => {
      if (checkItem.id == data.id) {
        resData.value[index].types.splice(indexs, 1);
      }
    });
  }
};

//拖拽相关

const refreshTable = () => {
  tableShow.value = false;
  nextTick(() => {
    tableShow.value = true;
    nextTick(() => {
      inintDrag();
    });
  });
};

const inintDrag = () => {
  nextTick(() => {
    let sortDom = document.querySelector(`#content_table_List .ant-table-tbody`);
    let dragged: dataSourceType[] = [];
    let related: dataSourceType[] = [];
    let IsCanDrag: boolean = true;
    let Oldindex: any = 0;
    Sortable.create(sortDom as HTMLElement, {
      disabled: false,
      //sort:true, // 给了就无法拖动
      //handle: ".ant-table-row",
      animation: 150,
      draggable: '.ant-table-row', // tr拖动
      dragClass: "dragClass",
      dataIdAttr: "chosenClass", //给停靠位置添加的class（可以给这个class定义样式
      ghostClass: "ghostClass",
      forceFallback: false,
      fallbackClass: "sortable-fallback",  // 当使用forceFallback的时候，被复制的dom的css类名
      onStart({ item }) {
        let targetRowKey = item.dataset.rowKey;
        let targetRowData =
          resData.value.filter((item: any, index: number) => (targetRowKey == item.id))[0] || [];

        dataList.value.forEach((item_data: any, index: number) => {
          if (targetRowKey == item_data.id) {
            Oldindex = index + 1;
          }
        })
      },
      onMove(evt) {
        dragged = resData.value.filter(
          (item: any) => evt.dragged.dataset.rowKey == item.id
        );
        related = resData.value.filter(
          (item: any) => evt.related.dataset.rowKey == item.id
        );
        if ((dragged[0]?.isTop && !related[0]?.isTop) || (!dragged[0]?.isTop && related[0]?.isTop)) {
          IsCanDrag = false;
          return false;
        } else {
          IsCanDrag = true;
        }

      },
      onEnd: ({ newIndex, item }: { newIndex: any; item: any }) => {
        let Parent: dataSourceType[] = resData.value.filter(
          (data: any) => dragged[0]?.parentId == data.id
        );
        let Targetindex: number = newIndex;// 拖拽的元素和第Targetindex个子元素将要互换位置
        Parent[0] && Parent[0].children && Parent[0].children.forEach((data: any, index: number) => {
          if (related[0].id == data.id) {
            Targetindex = index
          }
        });
        let targetRowKey = item.dataset.rowKey;// 拖拽的元素
        let targetArray = []; // 获取拖拽元素的真正层级，会找到最上层的
        let dataListItem: dataSourceType = {};
        let targetItem: dataSourceType = {};
        let currentRowKey = "";
        let currentArray = [];
        let isNext = false;
        let notBelong = false;
        if (!(dragged[0]?.id && related[0]?.id)) {
          return
        }
        if (targetRowKey || targetRowKey == 0) {
          targetArray = getTargeIndex(dataList.value, targetRowKey.toString());
        }
        if (newIndex - 1 > 0) {// newIndex是从1开始的
          // 要替换的是哪个tr
          currentRowKey = (
            document.querySelectorAll(".ant-table-row")[+newIndex - 1 - 1] as any
          ).dataset.rowKey;
          // 判断下一个tr是否存在，不存在就无法进行拖拽
          if (document.querySelectorAll(".ant-table-row")[+newIndex - 1 + 1]) {
            let raltedEleKey = resData.value.filter(
              (item: any) =>
                (
                  document.querySelectorAll(".ant-table-row")[
                  +newIndex - 1 + 1
                  ] as any
                ).dataset.rowKey == item.id
            );
            if (raltedEleKey[0]?.parentId == dragged[0]?.parentId) {
              currentRowKey = (
                document.querySelectorAll(".ant-table-row")[+newIndex - 1 + 1] as any
              ).dataset.rowKey;
              isNext = true;
            }
          }
        }
        targetArray.forEach((item: string | number, index: number) => {
          item = +item;
          if (index < targetArray.length - 1) {
            if (!index) {
              targetItem = dataList.value[item];
            } else {
              targetItem = targetItem.children[item];
            }
          } else {
            if (!index) {
              // targetArray是[0,1,1]这样的嵌套，标明是第一层，第二层，第三层..
              targetItem = JSON.parse(JSON.stringify(dataList.value[item]));
              if (targetItem.children) {
                //查看第一层级的children是否看有目标替换的元素的key值
                notBelong = judgeBelong(currentRowKey, targetItem.children);
              }
              if (!notBelong) {
                // 如果第一层级的children里不包含，则直接把这个item删除
                dataList.value.splice(item, 1);
              }
            } else {
              let calcItem = JSON.parse(
                JSON.stringify(targetItem.children[item])
              );
              if (calcItem.children) {
                notBelong = judgeBelong(currentRowKey, calcItem.children);
              }
              if (!notBelong) {
                targetItem.children.splice(item, 1);
                targetItem = calcItem;
              }
            }
          }
        });
        if (!notBelong) {
          if (newIndex > 0) {
            if (currentRowKey) {
              currentArray = getTargeIndex(
                dataList.value,
                currentRowKey.toString()
              );
            }
            currentArray.forEach((item: string | number, index: number) => {
              item = +item;
              if (index < currentArray.length - 1) {
                if (!index) {
                  dataListItem = dataList.value[item];
                } else {
                  dataListItem = dataListItem.children[item];
                }
              } else {
                if (!index) {
                  if (!isNext) {
                    dataList.value.splice(item + 1, 0, targetItem);
                  } else {
                    dataList.value.splice(item, 0, targetItem);
                  }
                } else {
                  if (!isNext) {
                    dataListItem.children.splice(item + 1, 0, targetItem);
                  } else {
                    dataListItem.children.splice(item, 0, targetItem);
                  }
                }
              }
            });
          } else {
            dataList.value.unshift(targetItem);
          }
        }
        if (Oldindex === newIndex) {
          return
        }
        if (!IsCanDrag) {
          refreshTable();
          message.warning("不可拖拽互换位置！！");
          return;
        }
        dataList.value = JSON.parse(JSON.stringify(dataList.value));
        refreshTable();
        const draggData = { id: dragged[0]?.id, toId: related[0]?.id, isBefore: Oldindex > Targetindex }
        dragEnd(draggData)
        // message.success("拖拽互换位置成功！！");
      },
    });
  })

};

// 拖拽变换表格数据
const dragEnd = async (param: dataSourceType) => {
  const contentIds = resData.value.length && resData.value.map((item: any) => item.id)
  await request
    .getContentDragSort({ ...param, contentIds })
    .then((res: dataSourceType) => {
      if (res.code == "00000 00000") {
        message.success(res.message);
        let prs = {
          pageCurrent: pageCurrent.value,
          pageSize: pageSize.value,
        };
        changePage(prs);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};

const getTargeIndex: any = (
  list: dataSourceType[],
  id: string | number,
  arr = []
) => {
  return list.reduce((total: any, item, index) => {
    if (item.id.toString() === id) {
      return [...total, index];
    } else {
      if (item.children && item.children.length) {
        let childArr = getTargeIndex(item.children, id, [...arr, index]);
        if (childArr.length === [...arr, index].length) {
          childArr = total;
        }
        return childArr;
      } else {
        return total;
      }
    }
  }, arr);
};
const judgeBelong: any = (key: string | number, list = []) => {
  return list.find((item: dataSourceType) => {
    if (item.id.toString() === key) {
      return true;
    } else {
      return false;
    }
  });
};

//发布
const releaseRecord = async (item: any) => {
  if (!btnPerm.value.includes('publishAble')) return
  Modal.confirm({
    content: "您确定发布此内容？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "发布",
    onOk: async () => {
      fetchContentPublish([item.id]);
    },
    onCancel() { },
  });
};

//批量发布
const publishAll = async () => {
  Modal.confirm({
    content: "您确定发布选中的内容？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "发布",
    onOk: async () => {
      fetchContentPublish(rowSelection.value);
    },
    onCancel() { },
  });
};
//下线
const offlineRecord = async (item: any) => {
  if (!btnPerm.value.includes('offlineAble')) return
  Modal.confirm({
    content: "您确定下线此内容？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "下线",
    onOk: async () => {
      fetchContentOffline([item.id]);
    },
    onCancel() { },
  });
};
//批量下线
const offlineRecordAll = async () => {
  Modal.confirm({
    content: "您确定下线选中的内容？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "下线",
    onOk: async () => {
      fetchContentOffline(rowSelection.value);
    },
    onCancel() { },
  });
};
// 催办
const urgeRecords = async (item: any) => {
  Modal.confirm({
    content: "催办当前审核节点的审核用户，将以站内信或邮件或短信的形式通知到对应审核用户",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "催办",
    onOk: async () => {
      let params = {
        id: item.id
      }
      request.contentUrge(params).then((res: any) => {
        if (res.code == "00000 00000") {
          let prs = {
            pageCurrent: pageCurrent.value,
            pageSize: pageSize.value,
          };
          changePage(prs);
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      })
    },
    onCancel() { },
  });
};
// 查看审核进度
const auditProgress = (item: any) => {
  let params = {
    contentId: item.id
  }
  request.auditProgress(params).then((res: any) => {
    if (res) {
      router.push({
        path: '/config/workFlow/auditDetail',
        query: {
          id: res
        },
      });
    }


  })
}
// 撤回审核
const revocationRecords = async (item: any) => {
  let params = {
    id: item.id
  }
  Modal.confirm({
    title: "是否撤回审核？",
    content: "撤回审核后，需要重新发起审核，是否继续？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "撤回审核",
    onOk: async () => { //revokeWorkflow
      request
        .revokeWorkflow(params)
        .then((res: any) => {
          if (res.code == "00000 00000") {
            let prs = {
              pageCurrent: pageCurrent.value,
              pageSize: pageSize.value,
            };
            changePage(prs);
            message.success(res.message);
          } else {
            message.error(res.message);
          }
        })
    },
    onCancel() { },
  });
};
// 删除多个
const deleteSelectedAll = async (item: any) => {
  console.log(tagBaseTables.value.selectedRowKeys, "tagBaseTables.value.selectedRowKeys");
  Modal.confirm({
    content: "您确定将选中的内容移入回收站？",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      fetchContentRecycle(rowSelection.value)
    },
    onCancel() { },
  });
};

// 下线
const fetchContentOffline = async (ids: any) => {
  request
    .fetchContentOffline({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        let prs = {
          pageCurrent: pageCurrent.value,
          pageSize: pageSize.value,
        };
        changePage(prs);
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 发布
const fetchContentPublish = async (ids: any) => {
  request
    .fetchContentPublish({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        let prs = {
          pageCurrent: pageCurrent.value,
          pageSize: pageSize.value,
        };
        changePage(prs);
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 更改内容类型
const fetchContentChangeTypes = async (data: any, contentIds: any) => {
  request
    .fetchContentChangeTypes({ typeIds: data, contentIds: contentIds })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        // let prs = {
        //   pageCurrent: pageCurrent.value,
        //   pageSize: pageSize.value,
        // };
        // changePage(prs);
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
// 删除
const fetchContentRecycle = async (ids: any) => {
  request
    .fetchContentRecycle({ ids })
    .then((res: any) => {
      if (res.code == "00000 00000") {
        let prs = {
          pageCurrent: pageCurrent.value,
          pageSize: pageSize.value,
        };
        changePage(prs);
        message.success(res.message);
      } else {
        message.error(res.message);
      }
    })
    .catch((err: any) => {
      throw new Error(err);
    });
};
const handleMenuClick = async (params: any) => {
  if (params.key == 1) {
    // 置顶;
    request
      .fetchContentTop({ ids: tagBaseTables.value.selectedRowKeys })
      .then((res: any) => {
        if (res.code == "00000 00000") {
          let prs = {
            pageCurrent: pageCurrent.value,
            pageSize: pageSize.value,
          };
          changePage(prs);
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      })
      .catch((err: any) => {
        throw new Error(err);
      });
  } else if (params.key == 2) {
    // 取消置顶;
    request
      .fetchContentTopCancell({ ids: tagBaseTables.value.selectedRowKeys })
      .then((res: any) => {
        if (res.code == "00000 00000") {
          let prs = {
            pageCurrent: pageCurrent.value,
            pageSize: pageSize.value,
          };
          changePage(prs);
          message.success(res.message);
        } else {
          message.error(res.message);
        }
      })
      .catch((err: any) => {
        throw new Error(err);
      });
  } else if (params.key == 3) {
    // 移动;
    isMoveVisible.value = true;
    contentId.value = tagBaseTables.value.selectedRowKeys;
  } else if (params.key == 4) {
    // 排序;
    isSortVisible.value = true;
    contentId.value = tagBaseTables.value.selectedRowKeys;
  } else if (params.key == 5) {
    // 推送;
    isPushVisible.value = true;
    contentId.value = tagBaseTables.value.selectedRowKeys;
  } else if (params.key == 6) {
    // 归档;
    Modal.confirm({
      content: "您确定归档选中的内容？",
      centered: true,
      icon: createVNode("i", {
        class: "iconfont icon-warn warning_ICON",
      }),
      cancelText: "取消",
      okText: "确定",
      onOk: async () => {
        request
          .fetchContentFile({ ids: tagBaseTables.value.selectedRowKeys })
          .then((res: any) => {
            if (res.code == "00000 00000") {
              let prs = {
                pageCurrent: pageCurrent.value,
                pageSize: pageSize.value,
              };
              changePage(prs);
              message.success(res.message);
            } else {
              message.error(res.message);
            }
          })
          .catch((err: any) => {
            throw new Error(err);
          });
      },
      onCancel() { },
    });
  }
};

// 单个归档
const singleMergeDom = (item: any) => {
  if (!btnPerm.value.includes('archiveAble')) return
  tagBaseTables.value.selectedRowKeys = [item.id]
  handleMenuClick({ key: 6 })
}
// 移动
const moveRecords = async (item: any) => {
  if (!btnPerm.value.includes('moveAble')) return
  isMoveVisible.value = true;
  contentId.value = [item.id];
};

// 页面浏览
const viewPage = (item: any, type: number) => {
  // console.log(item, 'item')
  if (type === 1 && item && btnPerm.value.includes('previewAble')) {
    window.open(item);
  } else if (type === 2 && item && btnPerm.value.includes('scanAble')) {
    window.open(item);
  } else {
    return
  }
}

// 推送
const pushRecord = async (item: any) => {
  if (!btnPerm.value.includes('pushAble')) return
  isPushVisible.value = true;
  contentId.value = [item.id];
  disableCheckboxId.value = item.channelId
};
// 浏览记录
const historyRecord = async (item: any) => {
  if (!btnPerm.value.includes('scanHistoryAble')) return
  isHistoryVisible.value = true;
  contentId.value = [item.id];
};

// 确认移动
const handleOk = (e: MouseEvent) => {
  isMoveVisible.value = false;
  isPushVisible.value = false;
  let prs = {
    pageCurrent: pageCurrent.value,
    pageSize: pageSize.value,
  };
  changePage(prs);
};
const selectColumn = (item: any) => {
  emit('selectColumn', [item.channelId])
};
// 详情
const eidtRecord = async (item: any) => {
  router.push({
    path: "/content/newContent",
    name: "内容详情",
    query: {
      contentId: item.id,
      channelId: item.channelId || null,
      id: item.modelId,
      modelName: item.modelName,
      previewPerm: !btnPerm.value.includes('previewAble') ? 1 : 0, // 1 没有按钮权限 0 有
    },
  });
};


// 单个置顶和取消置顶
const singleHandleTop = (record: any) => {
  if (record.isTop) {
    if (!btnPerm.value.includes('cancelTopAble')) return
  } else {
    if (!btnPerm.value.includes('topAble')) return
  }
  tagBaseTables.value.selectedRowKeys = [record.id]
  handleMenuClick({ key: record.isTop ? 2 : 1 })
}
// 删除单个
const confirmDelete = async (item: any) => {
  // deleteArr.value = [item.id];
  // deleteRecords(deleteArr.value);
};


// 相关内容
const correlationRecord = (item: any) => {
  if (!btnPerm.value.includes('relatedContentAble')) return
  contentIdDetail.value = item.id
  isCorrelationVisible.value = true;
};
// 操作记录
const operatingRecord = (item: any) => {
  if (!btnPerm.value.includes('operationHistoryAble')) return
  contentIdDetail.value = item.id
  isoperatingVisible.value = true;
};

const emit = defineEmits(["changePage", "selectColumn"]);
//切换分页器
const changePage = (data: { pageCurrent: any; pageSize: any }) => {
  emit("changePage", data);
  pageCurrent.value = data.pageCurrent;
  pageSize.value = data.pageSize;
  rowSelection.value = [];
};
const getRecordValue = (key: number) => {
  return key == 1
    ? "草稿"
    : key == 3
      ? "审核中"
      : key == 4
        ? "待发布"
        : key == 5
          ? "已发布"
          : key == 6
            ? "审核不通过"
            : key == 7
              ? "下线"
              : key == 8 && "归档";
};

//watch
watch(
  () => tagBaseTables.value?.selectedRowKeys,
  (newVal, oldVal) => {
    rowSelection.value = newVal;
  },
  { deep: true }
);
watch(
  () => contType.value,
  (newVal, oldVal) => {
    fetchContentChangeTypes(newVal, contentId.value);
  },
  { deep: true }
);
watch(
  () => props.configData.records,
  (newVal, oldVal) => {
    if (newVal.length) {
      resData.value = newVal;

      nextTick(() => {
        let obj = getTableScroll(20, "content_table_List", -42);
        scroll.y = obj.y;
        scroll.isFixed = obj.isFixed;
      });
    } else {
      resData.value = [];
    }
  },
  { deep: true }
);
watch(
  () => props.isOpen,
  (newVal, oldVal) => {
    console.log(newVal, 'newVal');
    let isOpen = ref(newVal);
    if (isOpen.value == false) {
      nextTick(() => {
        let obj = getTableScroll(20, "content_table_List", -42);
        scroll.y = obj.y;
        scroll.isFixed = obj.isFixed;
      });
    } else {
      nextTick(() => {
        let obj = getTableScroll(40, "content_table_List", 150);
        scroll.y = obj.y;
        scroll.isFixed = true;
      });
    }
  },
  { deep: true }
);

//onMounted
onMounted(() => {
  btnPerm.value = routerPerm();
  tableShow.value = true;
  nextTick(() => {
    inintDrag();
  })
  pageSize.value = props.pageSize || 20
  pageCurrent.value = props.pageCurrent || 1
})

</script>

<style lang="less" scoped>
.content_table_List {
  :deep(.ant-dropdown-button) {
    margin-right: 8px;
    margin-bottom: 8px;
  }

  :deep(.ant-table-cell) {
    // display: flex;
    align-items: center;
    // background: red;
  }

  :deep(table tr th.ant-table-selection-column) {
    text-align: left;
  }

  ::v-deep(.ant-table-row) {
    height: 56px;
    cursor: move;
    // 禁止文字被鼠标选中 
    moz-user-select: -moz-none;
    -moz-user-select: none;
    -o-user-select: none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

  .titleBox {
    display: flex;
    align-items: center;
    justify-items: center;
    // height: 29px;
    // line-height: 29px;
    // height: 18px;

    .titleTip {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .titleType {
      display: flex;
    }
  }

  .left-title {
    display: flex;
    flex-direction: row;
    align-items: center;

    .title-box {
      display: flex;
      flex-direction: row;
      align-items: center;

      .channelName-content {
        font-size: 14px;
        color: #00000073;
      }

      .title-text {
        margin-right: 8px;
        font-size: 14px;
        color: #000000D9;
        max-width: 208px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .icon-a-Pinnedtotop1 {
        font-size: 18px;
        line-height: 18px;
      }

      .title-text:hover {
        cursor: pointer;
        color: #1f6ded;
      }

      .title-text:active {
        color: #1f6ded;
      }
    }
  }


  .tabletypeImg {
    margin-right: 4px;
    width: 18px;
    height: 18px;
    // line-height: 18px;
  }

  background-color: #fff;

  .eidtRecords {
    margin-right: 16px;
  }

  .eidtRecords:hover {
    background: transparent;
  }

  .xwtype {
    font-size: 12px;
    line-height: 12px;
    padding: 1.5px 7px;
    border-radius: 2px;
  }

  .type3 {
    background-color: #edf7ff;
    color: #1f6ded;
    border: 1px solid #9cccff;
  }

  .type5 {
    background-color: #f6ffed;
    color: #389e0d;
    border: 1px solid #b7eb8f;
  }

  .type7 {
    background-color: rgba(0, 0, 0, 0.04);
    color: rgba(0, 0, 0, 0.45);
    border: 1px solid rgba(0, 0, 0, 0.15);
  }

  .type1 {
    background-color: #e6fffb;
    color: #08979c;
    border: 1px solid #87e8de;
  }

  .type4 {
    background-color: #fff7e6;
    color: #d46b08;
    border: 1px solid #ffd591;
  }

  .more {
    font-size: 14px;
    // color: red;
  }
}
</style>
<style lang="scss">
.a-content-btns-popover .ant-popover-inner-content {
  padding: 4px 0;
  display: flex;
  flex-direction: column;
}

.a-content-btns-popover .ant-popover-inner-content .eidtRecords {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 80px;
  height: 32px;
  padding-left: 12px;
}

.eidtRecords:hover {
  background-color: #0000000A;
}

#content_table_List {
  // margin-top: 16px;
  overflow: auto;
  height: 100%;
  padding: 16px;

  .ant-table-cell-fix-left,
  .ant-table-cell-fix-right {
    z-index: 1;
  }

  .ant-table-header {
    z-index: 2;
  }


  .ant-table-cell:nth-last-of-type(1) {
    text-align: right;
    margin-right: 16px;
    background-color: #fff;
  }

  .ant-table-thead .ant-table-cell:nth-last-of-type(1) {
    background-color: #fafafa;
  }
}

.contentTypeImg {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-content: center;

  .typeImgBox {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 32px;

    .typeImg {
      width: 18px;
      height: 18px;
      transform: translateY(3px);
    }

    span {
      margin-left: 8px;
      height: 14px;
      font-size: 14px;
      font-family: PingFang SC-Regular, PingFang SC;
      font-weight: 400;
      color: rgba(0, 0, 0, 0.85);
      // line-height: 18px;
    }
  }

  .checkboxs:first-child {
    display: flex;
    align-items: center;
    height: 32px;
  }


}

.disable {
  color: rgba(0, 0, 0, 0.25);
  cursor: not-allowed;
  // pointer-events:none;
}
</style>
